import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { Table, Button, Space, Card, Tag, message, Typography, Badge, Form, Input, Select, DatePicker, Divider } from 'antd';
import { PlusOutlined, ArrowLeftOutlined, RocketOutlined, CloseOutlined, PlusSquareOutlined, WarningOutlined } from '@ant-design/icons';
import { projectVersionApi, kubernetesApi, releaseApi } from '../services/api';
import Editor from '@monaco-editor/react';
import Header from '../components/layout/Header';
// 引入 js-yaml 库用于验证 YAML 格式
import jsYaml from 'js-yaml';
import './VersionListPage.css';

const { Title, Text } = Typography;

// 添加全局错误处理，防止 ResizeObserver 错误
if (typeof window !== 'undefined') {
  // 拦截控制台错误
  const originalConsoleError = console.error;
  console.error = (...args) => {
    if (args[0] && typeof args[0] === 'string' && args[0].includes('ResizeObserver loop')) {
      // 忽略 ResizeObserver 循环错误
      return;
    }
    originalConsoleError.apply(console, args);
  };

  // 拦截 window 错误事件
  window.addEventListener('error', (event) => {
    if (event && event.message && event.message.includes('ResizeObserver loop')) {
      event.stopImmediatePropagation();
      event.preventDefault();
      return false;
    }
  }, true);

  // 拦截 Promise 错误
  window.addEventListener('unhandledrejection', (event) => {
    if (event && event.reason && event.reason.message && event.reason.message.includes('ResizeObserver loop')) {
      event.stopImmediatePropagation();
      event.preventDefault();
      return false;
    }
  }, true);
}

// 编辑器实例存储
const editorInstances = {};

// 创建一个带有 YAML 语法高亮的编辑器组件
const SimpleYamlEditor = ({ value, onChange, height = '400px', readOnly = false, editorId, syncWithId, isValid = true }) => {
  // 添加样式标签以确保编辑器背景是黑色的
  React.useEffect(() => {
    // 创建样式标签
    const style = document.createElement('style');
    style.innerHTML = `
      .monaco-editor, 
      .monaco-editor .margin,
      .monaco-editor-background,
      .monaco-editor .inputarea.ime-input {
        background-color: #000000 !important;
      }
    `;
    style.id = 'monaco-editor-black-bg';
    
    // 检查是否已经存在该样式
    if (!document.getElementById('monaco-editor-black-bg')) {
      document.head.appendChild(style);
    }
    
    return () => {
      // 组件卸载时移除样式
      const existingStyle = document.getElementById('monaco-editor-black-bg');
      if (existingStyle) {
        document.head.removeChild(existingStyle);
      }
      
      // 清除编辑器实例
      if (editorId && editorInstances[editorId]) {
        delete editorInstances[editorId];
      }
    };
  }, [editorId]);

  return (
    <div style={{ 
      backgroundColor: '#000000', 
      padding: 0, 
      height,
      border: isValid === false ? '2px solid #ff4d4f' : 'none',
      position: 'relative'
    }}>
      {isValid === false && (
        <div style={{
          position: 'absolute',
          top: '5px',
          right: '5px',
          zIndex: 10,
          color: '#ff4d4f',
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          padding: '2px 8px',
          borderRadius: '4px',
          fontSize: '12px',
          display: 'flex',
          alignItems: 'center'
        }}>
          <WarningOutlined style={{ marginRight: '5px' }} />
          YAML 格式无效
        </div>
      )}
      <Editor
        height="100%"
        defaultLanguage="yaml"
        defaultValue={value || ''}
        value={value}
        onChange={onChange}
        options={{
          readOnly,
          minimap: { enabled: false },
          scrollBeyondLastLine: false,
          fontSize: 14,
          automaticLayout: true,
          wordWrap: 'on',
          theme: 'vs-dark',
          tabSize: 2
        }}
        className="yaml-editor"
        beforeMount={(monaco) => {
          // 设置编辑器背景色为黑色
          monaco.editor.defineTheme('black-theme', {
            base: 'vs-dark',
            inherit: true,
            rules: [],
            colors: {
              'editor.background': '#000000',
              'editorGutter.background': '#000000',
              'editorLineNumber.foreground': '#666666',
              'editorLineNumber.activeForeground': '#FFFFFF'
            }
          });
        }}
        onMount={(editor, monaco) => {
          // 编辑器加载后立即设置为黑色主题
          monaco.editor.setTheme('black-theme');
          
          // 强制刷新编辑器布局
          setTimeout(() => {
            editor.layout();
          }, 0);
          
          // 如果提供了编辑器ID，将实例存储起来
          if (editorId) {
            editorInstances[editorId] = editor;
            
            // 添加滚动事件监听器，实现同步滚动
            if (syncWithId) {
              editor.onDidScrollChange((e) => {
                const syncEditor = editorInstances[syncWithId];
                if (syncEditor && syncEditor !== editor) {
                  // 防止循环触发
                  if (syncEditor._lastScrollTop !== e.scrollTop) {
                    syncEditor._lastScrollTop = e.scrollTop;
                    syncEditor.setScrollTop(e.scrollTop);
                  }
                  if (syncEditor._lastScrollLeft !== e.scrollLeft) {
                    syncEditor._lastScrollLeft = e.scrollLeft;
                    syncEditor.setScrollLeft(e.scrollLeft);
                  }
                }
              });
            }
          }
        }}
      />
    </div>
  );
};

const VersionListPage = () => {
  const { projectId } = useParams();
  const navigate = useNavigate();  // 状态管理
  const [loading, setLoading] = useState(false);
  const [versions, setVersions] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 部署表单相关状态
  const [showDeployForm, setShowDeployForm] = useState(false);
  const [deploying, setDeploying] = useState(false);
  const [deployForm] = Form.useForm();

  // 编辑器相关状态
  const [showEditor, setShowEditor] = useState(false);
  const [editorMounted, setEditorMounted] = useState(false);

  // 展开行相关状态
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [selectedAction, setSelectedAction] = useState({});
  const [yamlValidStatus, setYamlValidStatus] = useState({}); // 用于跟踪 YAML 格式是否有效
  const [rollbackRevision, setRollbackRevision] = useState({});

  // 集群选项
  const [clusters] = useState([
    { value: 'cluster-1', label: '生产集群' },
    { value: 'cluster-2', label: '测试集群' },
  ]);

  // Chart 选项
  const [charts] = useState([
    { value: 'nginx', label: 'Nginx' },
    { value: 'mysql', label: 'MySQL' },
    { value: 'redis', label: 'Redis' },
  ]);

  // 项目信息
  const [projectInfo, setProjectInfo] = useState({
    name: '未命名项目',
    currentVersion: '1.0.0',
  });

  // 表单初始值
  const [formValues, setFormValues] = useState({
    project: '',
    version: '',
    cluster: '',
    namespace: 'default',
    chart: '',
    releaseName: '',
    yaml: 'apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: my-app\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: my-app\n  template:\n    metadata:\n      labels:\n        app: my-app\n    spec:\n      containers:\n      - name: my-app\n        image: nginx:latest\n        ports:\n        - containerPort: 80'
  });

  // 我们不再需要编辑器引用，因为我们使用的是简单的 TextArea

  // 处理 YAML 内容变化
  const [deployYamlValid, setDeployYamlValid] = useState(true);
  
  const handleYamlChange = (value) => {
    // 更新表单值
    setFormValues(prev => ({
      ...prev,
      yaml: value
    }));
    
    // 验证 YAML
    try {
      if (!value || !value.trim()) {
        setDeployYamlValid(false);
        return;
      }
      
      // 使用 js-yaml 验证 YAML 格式
      const options = {
        json: true,
        schema: 'DEFAULT_SAFE_SCHEMA',
        onWarning: (warning) => {
          console.log('YAML 解析警告:', warning);
        }
      };
      
      // 分割并验证每个文档
      const documents = value.split('---').filter(doc => doc.trim() !== '');
      
      if (documents.length === 0) {
        setDeployYamlValid(false);
        return;
      }
      
      // 验证每个文档
      for (const doc of documents) {
        if (doc.trim()) {
          jsYaml.load(doc, options);
        }
      }
      
      setDeployYamlValid(true);
    } catch (error) {
      console.error('YAML 解析失败:', error);
      setDeployYamlValid(false);
    }
  };

  // 监听表单值变化
  const handleFormChange = (changedValues, allValues) => {
    setFormValues(prev => ({
      ...prev,
      ...allValues
    }));
  };

  // 处理部署提交
  const handleDeploySubmit = async (values) => {
    try {
      setDeploying(true);

      // 直接使用表单中的YAML内容
      const currentYaml = values.yaml;
      console.log('部署参数:', { ...values, yaml: currentYaml });

      // 调用Kubernetes部署API
      const response = await kubernetesApi.deployYaml(
        currentYaml,
        values.namespace,
        parseInt(projectId), // 传递当前项目ID
        values.releaseName,
      );
      console.log('部署请求参数:', {
        releaseName: values.releaseName,
        projectId: parseInt(projectId), namespace: values.namespace
      });

      if (response && response.code === 200) {
        message.success('部署成功');
        setShowDeployForm(false);
        deployForm.resetFields();
        // 刷新版本列表
        fetchVersions(pagination.current, pagination.pageSize);
      } else {
        message.error(response?.message || '部署失败，请检查YAML配置');
      }
    } catch (error) {
      console.error('部署失败:', error);
      message.error('部署失败: ' + (error.message || '未知错误'));
    } finally {
      setDeploying(false);
    }
  };

  // 获取版本列表
  const fetchVersions = async (page = 1, size = 10) => {
    try {
      setLoading(true);
      // 使用 releaseApi 获取发布版本列表
      const response = await releaseApi.getReleases(page, size, parseInt(projectId));

      if (response && response.code === 200) {
        // 将 releaseName 映射为 versionName 以保持兼容性
        const formattedVersions = (response.data.records || []).map(version => ({
          ...version,
          versionName: version.releaseName,
          status: 'RELEASED', // 添加默认状态
          createdAt: version.createdAt,
          updatedAt: version.updatedAt
        }));

        setVersions(formattedVersions);
        setPagination({
          ...pagination,
          current: response.data.current || 1,
          total: response.data.total || 0,
        });
      } else {
        message.error(response?.message || '获取发布版本列表失败');
      }
    } catch (error) {
      console.error('获取发布版本列表失败:', error);
      message.error('获取发布版本列表失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 处理分页变化
  const handleTableChange = (pagination) => {
    fetchVersions(pagination.current, pagination.pageSize);
  };

  // 处理部署操作
  const handleDeploy = (version) => {
    // 这里添加部署逻辑
    message.info(`准备部署版本: ${version.versionName}`);
    // navigate(`/deploy/${version.id}`); // 可以跳转到部署页面
  };

  // 处理展开/收起行
  const handleExpandRow = (expanded, record) => {
    setExpandedRowKeys(expanded ? [record.id] : []);
    if (expanded) {
      // 默认选中重启选项
      setSelectedAction({
        ...selectedAction,
        [record.id]: 'restart'
      });
    }
  };

  // 处理选择操作
  const handleActionSelect = (action, recordId) => {
    setSelectedAction({
      ...selectedAction,
      [recordId]: action
    });
  };

  // 处理重启操作
  const handleRestart = (record) => {
    message.loading(`正在重启 ${record.versionName}...`);
    // 这里添加重启逻辑
    setTimeout(() => {
      message.success(`重启 ${record.versionName} 成功`);
      setExpandedRowKeys([]);
    }, 1500);
  };

  // 处理卸载操作
  const handleUninstall = (record) => {
    message.loading(`正在卸载 ${record.versionName}...`);
    // 这里添加卸载逻辑
    setTimeout(() => {
      message.success(`卸载 ${record.versionName} 成功`);
      setExpandedRowKeys([]);
    }, 1500);
  };

  // 处理回滚操作
  const handleRollback = (record) => {
    const revision = rollbackRevision[record.id];
    if (!revision) {
      message.error('请输入回滚的revision');
      return;
    }
    message.loading(`正在回滚 ${record.versionName} 到版本 ${revision}...`);
    // 这里添加回滚逻辑
    setTimeout(() => {
      message.success(`回滚 ${record.versionName} 到版本 ${revision} 成功`);
      setExpandedRowKeys([]);
    }, 1500);
  };

  // 处理输入回滚版本
  const handleRollbackRevisionChange = (e, recordId) => {
    setRollbackRevision({
      ...rollbackRevision,
      [recordId]: e.target.value
    });
  };

  useEffect(() => {
    fetchVersions();

    // 不再需要清理编辑器实例，因为我们使用的是 TextArea
    return () => {
      // 清理工作已经简化，因为我们不再使用 Monaco Editor
    };
  }, [projectId]);

  // 状态管理 - 升级编辑器
  const [upgradeYaml, setUpgradeYaml] = useState({});
  const [chartVersion, setChartVersion] = useState('0.1.28');

  // 编辑器引用 - 使用简单对象代替真正的 ref
  // 注意: 我们不再需要真正的 DOM 引用，因为我们使用简单的 TextArea 代替 Monaco Editor

  // 获取部署YAML数据
  const fetchDeploymentYaml = async (record) => {
    try {
      // 从后端 API 获取当前 release 的部署 YAML
      const response = await fetch(`/api/release/yaml/content/${record.id}`);
      const result = await response.json();
      
      if (result.code === 200 && result.data) {
        // 设置 YAML 内容
        const yamlContent = result.data;
        
        // 初始化 YAML 验证状态 - 默认为有效
        setYamlValidStatus(prev => ({
          ...prev,
          [record.id]: true
        }));
        
        // 设置 YAML 内容
        setUpgradeYaml(prev => ({
          ...prev,
          [record.id]: yamlContent
        }));
      } else {
        message.error(`获取 YAML 内容失败: ${result.message || '获取YAML内容失败'}`);
        // 如果获取失败，设置一个默认的 YAML 内容
        const errorContent = '# 未找到部署YAML内容';
        
        // 初始化 YAML 验证状态 - 默认为有效
        setYamlValidStatus(prev => ({
          ...prev,
          [record.id]: true
        }));
        
        // 设置默认内容
        setUpgradeYaml(prev => ({
          ...prev,
          [record.id]: errorContent
        }));
      }
    } catch (error) {
      console.error('获取YAML内容时出错:', error);
      message.error(`获取YAML内容失败: ${error.message}`);
      
      // 错误内容
      const errorContent = '# 获取YAML内容时出错';
      
      // 初始化 YAML 验证状态 - 默认为有效
      setYamlValidStatus(prev => ({
        ...prev,
        [record.id]: true
      }));
      
      // 设置错误内容
      setUpgradeYaml(prev => ({
        ...prev,
        [record.id]: errorContent
      }));
    }
  };

  // 处理升级提交
  const handleUpgradeSubmit = async (record) => {
    try {
      message.loading(`正在升级 ${record.versionName}...`);
      // 这里添加升级逻辑
      setTimeout(() => {
        message.success(`升级 ${record.versionName} 成功`);
        setExpandedRowKeys([]);
      }, 1500);
    } catch (error) {
      message.error(`升级失败: ${error.message}`);
    }
  };

  // 处理YAML编辑器变化 - 只更新右侧编辑器的内容
  const handleUpgradeYamlChange = (value, recordId) => {
    try {
      // 更新 YAML 内容
      setUpgradeYaml(prev => ({
        ...prev,
        [recordId]: value
      }));
      
      // 验证 YAML 内容
      validateYamlContent(value, recordId);
    } catch (error) {
      console.error('处理 YAML 更新时出错:', error);
      setYamlValidStatus(prev => ({
        ...prev,
        [recordId]: false
      }));
    }
  };

  // 验证 YAML 内容
  const validateYamlContent = (value, recordId) => {
    // 如果内容为空或只有空白字符，设置为无效
    if (!value || !value.trim()) {
      setYamlValidStatus(prev => ({
        ...prev,
        [recordId]: false // 空内容视为无效
      }));
      return false;
    }
    
    try {
      // 使用更宽松的解析选项
      const options = {
        json: true,               // 允许 JSON 格式
        schema: jsYaml.DEFAULT_SAFE_SCHEMA,  // 使用安全模式
        onWarning: (warning) => {
          console.log('YAML 解析警告:', warning);
        }
      };
      
      // 处理可能的多文档 YAML
      let isValid = true;
      
      // 检查是否包含多文档分隔符
      if (value.includes('---')) {
        // 分割并验证每个文档
        const documents = value.split('---').filter(doc => doc.trim() !== '');
        
        // 如果没有有效文档（只有注释或空行），视为无效
        if (documents.length === 0) {
          setYamlValidStatus(prev => ({
            ...prev,
            [recordId]: false
          }));
          return false;
        }
        
        // 验证每个文档
        for (const doc of documents) {
          if (doc.trim()) {
            try {
              jsYaml.load(doc, options);
            } catch (e) {
              isValid = false;
              console.error('多文档 YAML 解析失败:', e.message);
              break;
            }
          }
        }
      } else {
        // 单文档 YAML，直接解析
        jsYaml.load(value, options);
      }
      
      // 解析成功，更新状态为有效
      setYamlValidStatus(prev => ({
        ...prev,
        [recordId]: isValid
      }));
      return isValid;
    } catch (error) {
      console.error('YAML 解析失败:', error.message);
      setYamlValidStatus(prev => ({
        ...prev,
        [recordId]: false
      }));
      return false;
    }
  };

  // 处理Chart版本变化
  const handleChartVersionChange = (e) => {
    setChartVersion(e.target.value);
  };

  // 不再需要定义这些变量，因为我们已经不使用 Monaco Editor

  // 展开行时获取YAML数据
  useEffect(() => {
    const fetchYamlForExpandedRow = async () => {
      if (expandedRowKeys.length > 0) {
        const recordId = expandedRowKeys[0];
        const record = versions.find(v => v.id === recordId);

        if (record && selectedAction[recordId] === 'upgrade') {
          // 如果还没有获取过YAML内容，则调用API获取
          if (!upgradeYaml[recordId]) {
            await fetchDeploymentYaml(record);
          }
          
          // 确保 record.originalYaml 被设置为原始YAML内容
          // 这是关键：我们只在第一次加载时设置 originalYaml，后续不再更新它
          if (upgradeYaml[recordId] && !record.originalYaml) {
            record.originalYaml = upgradeYaml[recordId];
          }
        }
      }
    };

    fetchYamlForExpandedRow();
  }, [expandedRowKeys, selectedAction, upgradeYaml]);

  // 渲染展开行内容
  const expandedRowRender = (record) => {
    const currentAction = selectedAction[record.id] || 'restart';

    return (
      <div className="expanded-row-content">
        <div className="expanded-row-container">
          <div className="action-options">
            <div className="tab-button-group">
              <Button
                type="text"
                onClick={() => handleActionSelect('restart', record.id)}
                className={`tab-button ${currentAction === 'restart' ? 'active' : ''}`}
              >
                重启
              </Button>
              <Button
                type="text"
                onClick={() => handleActionSelect('upgrade', record.id)}
                className={`tab-button ${currentAction === 'upgrade' ? 'active' : ''}`}
              >
                升级
              </Button>
              <Button
                type="text"
                onClick={() => handleActionSelect('rollback', record.id)}
                className={`tab-button ${currentAction === 'rollback' ? 'active' : ''}`}
              >
                回滚
              </Button>
              <Button
                type="text"
                onClick={() => handleActionSelect('uninstall', record.id)}
                className={`tab-button ${currentAction === 'uninstall' ? 'active' : ''}`}
              >
                卸载
              </Button>
            </div>
          </div>

          <div className="action-content">
            {currentAction === 'restart' && (
              <>
                <div className="action-confirmation">确定重启吗？</div>
                <Button type="primary" shape="round" onClick={() => handleRestart(record)}>重启</Button>
              </>
            )}

            {currentAction === 'uninstall' && (
              <>
                <div className="action-confirmation">确定卸载吗？</div>
                <Button type="primary" danger shape="round" onClick={() => handleUninstall(record)}>卸载</Button>
              </>
            )}

            {currentAction === 'rollback' && (
              <>
                <div className="rollback-input">
                  <Input
                    placeholder="输入回滚的revision"
                    value={rollbackRevision[record.id] || ''}
                    onChange={(e) => handleRollbackRevisionChange(e, record.id)}
                    style={{ width: 200, marginRight: 16 }}
                  />
                  <Button type="primary" shape="round" onClick={() => handleRollback(record)}>回滚</Button>
                </div>
              </>
            )}

            {currentAction === 'upgrade' && (
              <div className="upgrade-container">
                <div className="chart-version-input">
                  <label>chartVersion: </label>
                  <Input
                    value={chartVersion}
                    onChange={handleChartVersionChange}
                    style={{ width: 100, marginRight: 16 }}
                  />
                  <Button
                    type="primary"
                    onClick={() => handleUpgradeSubmit(record)}
                    className="upgrade-button"
                  >
                    升级
                  </Button>
                </div>

                <div className="editors-container">
                  <div className="editors-header">
                    <div className="editor-header">Original Values</div>
                    <div className="editor-header">Modify Values</div>
                  </div>
                  <div className="editors-content">
                    <div className="editor-wrapper">
                      <SimpleYamlEditor
                        height="500px"
                        value={record.originalYaml || upgradeYaml[record.id] || ''}
                        onChange={() => {}}
                        readOnly={true}
                        editorId={`original-${record.id}`}
                        syncWithId={`modify-${record.id}`}
                      />
                    </div>
                    <div className="editor-wrapper">
                      <SimpleYamlEditor
                        height="500px"
                        value={upgradeYaml[record.id] || ''}
                        onChange={(value) => handleUpgradeYamlChange(value, record.id)}
                        readOnly={false}
                        editorId={`modify-${record.id}`}
                        syncWithId={`original-${record.id}`}
                        isValid={yamlValidStatus[record.id]}
                      />
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  const columns = [
    {
      title: 'release',
      dataIndex: 'versionName',
      key: 'versionName',
      render: (text, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <PlusSquareOutlined
            className="expand-icon"
            onClick={(e) => {
              e.stopPropagation();
              const isExpanded = expandedRowKeys.includes(record.id);
              handleExpandRow(!isExpanded, record);
            }}
            style={{
              marginRight: '8px',
              fontSize: '16px',
              color: expandedRowKeys.includes(record.id) ? '#1890ff' : '#8c8c8c',
              cursor: 'pointer'
            }}
          />
          <Button type="link" onClick={() => navigate(`/project/${projectId}/version/${record.id}`)} style={{ padding: 0, height: 'auto' }}>
            {text}
          </Button>
        </div>
      ),
    },
    {
      title: 'chart',
      dataIndex: 'chartName',
      key: 'chartName',
      render: (text) => text || 'common-java',
    },
    {
      title: 'revision',
      dataIndex: 'revision',
      key: 'revision',
      render: (text) => text || Math.floor(Math.random() * 100),
    },
    {
      title: '环境/集群/命名空间',
      dataIndex: 'environment',
      key: 'environment',
      render: (_, record) => {
        const env = record.environment || 'PRO';
        return (
          <div>
            <Tag color="success">{env}</Tag> {record.namespace || '移动/ai'}
          </div>
        );
      },
    },
    {
      title: '镜像',
      dataIndex: 'image',
      key: 'image',
      render: (_, record) => {
        const imageName = record.image || `${record.versionName}:${record.versionCode || '1.0'}`;
        return imageName;
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (text) => text || new Date().toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: () => (
        <a href="#" className="action-link">日志</a>
      ),
    },
  ];


  return (
    <div className="version-list-page">
      <div className="version-list-container">
        <div className="page-header">
          {!showDeployForm ?

            <div className="header-actions">
              <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                <Button
                  type="text"
                  icon={<ArrowLeftOutlined />}
                  onClick={() => navigate(`/project/${projectId}`)}
                >
                  返回项目
                </Button>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => setShowDeployForm(!showDeployForm)}
                >
                  {showDeployForm ? '取消部署' : '新增部署'}
                </Button>
              </div>
            </div>
            : <></>
          }
          {/* 部署表单 */}
          {showDeployForm && (
            <Card
              title="部署新版本"
              className="deploy-form-card"
            >
              <Form
                form={deployForm}
                layout="vertical"
                onFinish={handleDeploySubmit}
                onValuesChange={handleFormChange}
                initialValues={formValues}
              >
                <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
                  {/* 取消部署按钮 */}
                  <div className="cancel-deploy-button-section" style={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Button
                      onClick={() => setShowDeployForm(false)}
                      icon={<CloseOutlined />}
                    >
                      取消部署
                    </Button>
                  </div>
                  <div style={{ display: 'flex', gap: '12px' }}>
                    {/* 表单字段 - 每行两个字段，共三行 */}
                    <div className="form-fields-section" style={{ flex: '1' }}>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', maxWidth: '90%' }}>
                        <Form.Item
                          name="project"
                          label="项目"
                          rules={[{ required: false, message: '请选择项目' }]}
                          style={{ width: '90%' }}
                        >
                          <Input placeholder="项目名称" disabled value={projectInfo.name} />
                        </Form.Item>

                        <Form.Item
                          name="version"
                          label="版本号"
                          rules={[{ required: false, message: '请选择版本' }]}
                          style={{ width: '90%' }}
                        >
                          <Select placeholder="请选择版本">
                            {versions.map(version => (
                              <Select.Option key={version.id} value={version.versionName}>
                                {version.versionName}
                              </Select.Option>
                            ))}
                          </Select>
                        </Form.Item>

                        <Form.Item
                          name="cluster"
                          label="集群"
                          rules={[{ required: false, message: '请选择集群' }]}
                          style={{ width: '90%' }}
                        >
                          <Select placeholder="请选择集群">
                            {clusters.map(cluster => (
                              <Select.Option key={cluster.value} value={cluster.value}>
                                {cluster.label}
                              </Select.Option>
                            ))}
                          </Select>
                        </Form.Item>

                        <Form.Item
                          name="namespace"
                          label="命名空间"
                          rules={[{ required: false, message: '请选择命名空间' }]}
                          style={{ width: '90%' }}
                        >
                          <Select placeholder="请选择命名空间">
                            <Select.Option value="default">默认</Select.Option>
                            <Select.Option value="kube-system">kube-system</Select.Option>
                            <Select.Option value="production">production</Select.Option>
                          </Select>
                        </Form.Item>

                        <Form.Item
                          name="chart"
                          label="Chart"
                          rules={[{ required: false, message: '请选择Chart' }]}
                          style={{ width: '90%' }}
                        >
                          <Select placeholder="请选择Chart">
                            {charts.map(chart => (
                              <Select.Option key={chart.value} value={chart.value}>
                                {chart.label}
                              </Select.Option>
                            ))}
                          </Select>
                        </Form.Item>

                        <Form.Item
                          name="releaseName"
                          label="Release Name"
                          rules={[{ required: true, message: '请输入Release名称' }]}
                          style={{ width: '90%' }}
                        >
                          <Input placeholder="请输入Release名称" />
                        </Form.Item>
                      </div>
                    </div>

                    {/* YAML编辑器 - 占满右侧空间 */}
                    <div className="yaml-editor-section" style={{ flex: '1' }}>
                      <Form.Item
                        name="yaml"
                        label="YAML配置"
                        rules={[{
                          required: true,
                          validator: (_, value) => {
                            if (!value || value.trim() === '') {
                              return Promise.reject(new Error('请输入YAML配置'));
                            }
                            if (!deployYamlValid) {
                              return Promise.reject(new Error('YAML格式无效，请检查'));
                            }
                            return Promise.resolve();
                          }
                        }]}
                        style={{ height: '100%' }}
                      >
                        <SimpleYamlEditor
                          height="300px"
                          value={formValues.yaml}
                          onChange={handleYamlChange}
                          isValid={deployYamlValid}
                        />
                      </Form.Item>
                    </div>
                  </div>
                </div>
                <div style={{ marginTop: '16px', textAlign: 'right' }}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={deploying}
                    style={{ marginRight: 8 }}
                  >
                    确认部署
                  </Button>
                  <Button
                    onClick={() => setShowDeployForm(false)}
                    disabled={deploying}
                  >
                    取消
                  </Button>
                </div>
              </Form>
            </Card>
          )}
        </div>

        <div className="content-section">
          <div className="version-table-container">
            <Table
              columns={columns}
              dataSource={versions}
              rowKey="id"
              loading={loading}
              pagination={false}
              onChange={handleTableChange}
              className="version-table"
              size="middle"
              bordered={false}
              rowClassName={() => 'version-table-row'}
              style={{ backgroundColor: '#fff' }}
              expandable={{
                expandedRowRender,
                expandedRowKeys,
                expandRowByClick: false,
                expandIcon: () => null // 不显示默认的展开图标，我们使用自定义的图标
              }}
            />
          </div>

          {/* 下方留出的区域 */}
          <div className="deployment-area">
            <div className="deployment-area-content">
              {expandedRowKeys.length === 0 && (
                <div className="empty-deployment-message">
                  <div className="message-icon">
                    <RocketOutlined />
                  </div>
                  <div className="message-text">
                    点击列表中的加号图标，展开部署操作面板
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VersionListPage;
